package org.agile.grenoble.resources;

import java.sql.SQLException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MultivaluedMap;

import org.agile.grenoble.data.AnswersStorage;
import org.agile.grenoble.data.IAnswersStorage;
import org.agile.grenoble.data.StorageException;
import org.agile.grenoble.data.xml.QuestionsReader;
import org.agile.grenoble.questions.QuestionsType;
import org.apache.xmlbeans.XmlException;

/**
 * commentaire
 */
@Path("/storeAnswers")
public class AnswersStorageService {

  /**
   * commentaire
   */
  // The Java method will process HTTP GET requests
  @POST
  // The Java method will produce content identified by the MIME Media
  // type "text/plain"
  @Produces("application/xml")
  public String getClichedMessage(MultivaluedMap<String, String> params) {
    try {
      System.out.println("I'm in the post ");
      String answers = params.getFirst("answers");
      int pUserId = Integer.parseInt(params.getFirst("userId"));
      System.out.println("I'm in the post : " + pUserId);
      System.out.println("I'm in the post : " + answers);
      //QuestionsDocument doc = QuestionsReader.getDocumentFromString(answers);
      //QuestionsType questions = doc.getQuestions() ;
      QuestionsType questions = QuestionsReader.getQuestionsFromString(answers);
      System.out.println("coucou=> " + questions.sizeOfQuestionArray());
      IAnswersStorage storage = new AnswersStorage();
      storage.initializeDB(questions);
      storage.storeAnswers(questions, pUserId);
    } catch (StorageException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (XmlException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //return answers ;
    return "<status>OK</status>";
  }
}
